package com.customization.api.e9sso.cmd;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;

import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;

import weaver.conn.RecordSet;
import weaver.general.AES;
import weaver.general.Util;
import weaver.hrm.User;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;



public class SsoTokenCmd4Kb202008 extends AbstractCommonCommand<Map<String,Object>> {

    public SsoTokenCmd4Kb202008(User user, Map<String,Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
       String  appid=Util.null2String(params.get("appid"));

        Map<String, Object> apidatas = new HashMap<String, Object>();
        if("".equals(appid)){
            apidatas.put("status",false);
            apidatas.put("msg","appid不能为空或者没要找到对应的用户");
            return apidatas;
        }

        RecordSet rs= new RecordSet();

        String ip=Util.null2String(params.get("param_ip"));


        String allowip=Util.null2String(rs.getPropValue("WeaverLoginClient",appid));
        if(allowip.contains("8.8.8.8")){

        }else{
            if(!allowip.contains(ip)){
                apidatas.put("status",false);
                apidatas.put("msg","当前访问的IP:"+ip+"无访问权限！");
                return apidatas;

            }
        }

        try {
            String workcode=Util.null2String(params.get("workcode"));
            Console.log("输入参数:"+params);
            String userid="";
            rs.execute("select * from hrmresource where workcode='"+workcode+"'  and   (accounttype =0 or accounttype is null)");
            if(rs.next()){
                userid=rs.getString("id");
            }

            //如果查询不到员工编号，则按照登录名查询
            if(userid.equals("")){
                rs.execute("select * from hrmresource where loginid='"+workcode+"'  and   (accounttype =0 or accounttype is null)");
                if(rs.next()){
                    userid=rs.getString("id");
                }
            }

            if("".equals(userid)){
                apidatas.put("status",false);
                apidatas.put("msg","编号workcode不能为空或者没要找到对应的用户");
                return apidatas;
            }else {


                        //ECOLOGY返回的token
                        Console.log(appid+"===>开始获取token");
                        Map tokeninfo=getApiToken(appid,userid);
                        Console.log(appid+"===>获取token结果:"+tokeninfo.toString());
                        if(!(boolean)tokeninfo.get("status")) {
                            apidatas.put("status", false);
                            apidatas.put("errorInfo",tokeninfo.get("msg"));
                        }else{
                            apidatas.put("status", true);
                            apidatas.put("apiToken", (String)tokeninfo.get("token"));
                            apidatas.put("userId",   (String)tokeninfo.get("encryptUserid"));
                            apidatas.put("ssoToken", getSsoToken(appid,workcode,ip));
                            apidatas.put("createNodeID", getCreateNodeID(Util.null2String(params.get("requestId"))));
                        }

                return apidatas;
            }
        } catch (Exception e) {
            apidatas.put("status",false);
            apidatas.put("msg",e.toString());
            e.printStackTrace();
        }
        return apidatas;
    }


public String getCreateNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id and nodetype=0 and workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"'");
        rs.first();

        return rs.getString("nodeid");
    }
/**
 *
 * @param appid 应用ID
 * @param workcode  员工编号
 * @param ip  IP地址
 * @return
 */
public String getSsoToken(String appid,String workcode,String ip) {
        try {
        String loginid = "";
        RecordSet rst = new RecordSet();
        if (!workcode.equals("")) {

        rst.execute("select * from hrmresource where workcode ='" + workcode + "'");
        if (rst.next()) {
        loginid = rst.getString("loginid");
        }
        }

        if(loginid.equals("")){
        rst.execute("select * from hrmresource where loginid='"+workcode+"'");
        if(rst.next()){
        loginid = rst.getString("loginid");
        }
        }


        String salt = "yjcust";

        // RecordSet var19 = new RecordSet();
        //var19.executeQuery("select * from weaver_sso where token_isuse='1'", new Object[0]);
        //if (!var19.next()) {
        //   return "appid:" + appid + " has not permission to use!!!";
        //}

        if (loginid == null || "".equals(loginid)) {
        Console.log(" has no  loginidTemp account: " + workcode + "!!!");
        return " has no  account: " + workcode;
        }

        String datatime = (new Date()).getTime() + "";
        String token = AES.encrypt(loginid + "|" + datatime + "|" + appid, salt);
        RecordSet var24 = new RecordSet();
        var24.executeQuery("select * from hrmresource where loginid=? ", new Object[]{loginid});

        if (var24.next()) {
        var24.execute("select max(id ) maxid from sso_login_oa ");
        var24.next();
        String maxid = var24.getString("maxid");
        if ("".equals(maxid)) {
        maxid = "1";
        } else {
        maxid = Integer.valueOf(maxid) + 1 + "";
        }
        var24.executeUpdate("insert into sso_login_oa values(?,?,?,'0',?,?,'','','' )", new Object[]{maxid, loginid, loginid, datatime, token});

        return token;
        } else {
        return "has no account: " + loginid + "!!!";
        }

        } catch (Exception e) {
        e.printStackTrace();
        Console.log(e.toString());
        }
        return "";
        }

    //===========================2011.13 Start



    private static final String hostaddress="http://10.20.12.118" ;
    public static  Map<String,Object>  getApiToken(String appId,String userid){
        Map<String,Object> result = new HashMap<>();

        //1.调用ecology注册接口,根据appid进行注册,将返回服务端公钥和Secret信息
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();
        String data = HttpRequest.post(hostaddress + "/api/ec/dev/auth/regist")
                .header("appid",appId)
                .header("cpk",publicKey)
                .timeout(2000)
                .execute().body();
        result=JSONUtil.parseObj(data);

        if(!(boolean)result.get("status")){
            // 打印ECOLOGY响应信息
            System.out.println("Regist失败："+result.toString());
            return result;
        }
        String spk=StrUtil.nullToEmpty((String)result.get("spk"));
        String secrit=StrUtil.nullToEmpty((String)result.get("secrit"));


        // 公钥加密,所以RSA对象私钥为null
        rsa = new RSA(null,spk);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(secrit,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
        //调用ECOLOGY系统接口进行注册
        data = HttpRequest.post(hostaddress+ "/api/ec/dev/auth/applytoken")
                .header("appid",appId)
                .header("secret",encryptSecret)
                .header("time","3600")
                .execute().body();
        result=JSONUtil.parseObj(data);

        if(!(boolean)result.get("status")){
            // 打印ECOLOGY响应信息
            System.out.println("申请token失败："+result.toString());

        }


        String encryptUserid = rsa.encryptBase64(userid,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
        result.put("encryptUserid",encryptUserid);
        return result;
    }

}
